<?php

namespace App\Services;

use App\Http\Middleware\RBACMiddleware;
use App\Models\Admin;
use App\Repository\Contracts\AdminRepository;
use App\Repository\Contracts\MenuRepository;
use App\Repository\Contracts\PermissionRepository;

class AdminService
{
    /**
     * @var AdminRepository
     */
    protected $adminRepository;

    /**
     * @var PermissionRepository
     */
    protected $permissionRepository;

    /**
     * @var MenuRepository
     */
    protected $menuRepository;

    public function __construct(AdminRepository $adminRepository, PermissionRepository $permissionRepository, MenuRepository $menuRepository)
    {
        $this->adminRepository = $adminRepository;
        $this->permissionRepository = $permissionRepository;
        $this->menuRepository = $menuRepository;
    }

    public function getAdmins()
    {
        return $this->adminRepository->findAdminsByPage();
    }

    public function getAdmin($id)
    {
        return $this->adminRepository->find($id);
    }

    public function storeAdmin($data)
    {
        return $this->adminRepository->create($data);
    }

    public function updateAdmin($id, $data)
    {
        return $this->adminRepository->update($id, $data);
    }

    public function deleteAdmin($id)
    {
        return $this->adminRepository->deleteById($id);
    }

    /**
     * 获取权限信息
     * 返回用户的权限列表，角色列表，以及是否是超级管理员信息。
     *
     * @param Admin $admin
     * @return array
     */
    public function getPermissionRelatedInfo(Admin $admin)
    {
        $isSuper = $this->isSuperAdmin($admin);

        return $isSuper ? $this->permissionRepository->all() : $admin->permissions()->get();
    }

    public function assignByType($data)
    {
        $data['id_or_ids'] = json_decode($data['id_or_ids'], true);

        if (is_array($data['id_or_ids'])) {
            return $this->adminRepository->assignToRoles($data['id'], $data['id_or_ids']);
        }

        return $this->adminRepository->assignToPermission($data['id'], $data['id_or_ids']);
    }

    public function isSuperAdmin(Admin $admin)
    {
        return $admin->hasRole(RBACMiddleware::SUPER_ROLE);
    }

    public function findAdminRolesById($id)
    {
        $admin = $this->adminRepository->find($id);

        return $admin->roles;
    }

}